package com.hi5.stexviewer;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.hi5.stexviewer.message.CallCenter;
import com.hi5.stexviewer.message.Message;
import com.hi5.stexviewer.message.MessageType;
import com.hi5.stexviewer.message.SignalMessage;

/**
 * Entry point of Stock Exchange Viewer a.k.a StexViewer.
 *
 * @author mate
 *
 */
public class StexViewerApp implements ApplicationContextAware {
    private static final String MAIN_FRAME_NAME = "mainFrame";

    private static final Logger LOGGER = LoggerFactory.getLogger(StexViewerApp.class);

    private ApplicationContext applicationContext;


    public static void main(String[] args) {
        LOGGER.debug("StexViewer is staring up!");
        LOGGER.debug("Building context...");

        ApplicationContext context = new ClassPathXmlApplicationContext("classpath*:/conf/spring/context-*.xml");
        final StexViewerApp app = context.getBean(StexViewerApp.class);

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                app.showGui();
                app.sendEmptyMessage(MessageType.APPLICATION_START);
            }
        });
    }

    private void showGui() {
        JFrame main = applicationContext.getBean(MAIN_FRAME_NAME, JFrame.class);
        main.setVisible(true);
    }
    
    private void sendEmptyMessage(MessageType type) {
        CallCenter callCenter = applicationContext.getBean(CallCenter.class);
        callCenter.send(new SignalMessage(type));
    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
